package com.wwy.readwrite.config;

/**
 * @author 王伟羽
 * @program: readwrite-demo
 * @description:
 * @create: 2025/02/08
 */

import com.wwy.readwrite.utlis.DynamicDataSourceHolder;
import org.apache.ibatis.executor.keygen.SelectKeyGenerator;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.Locale;
import java.util.regex.Pattern;

/**
 * mybatis拦截器
 */
@Intercepts(
        //mybatis会将增删改的操作封装在update里面，所以insert和delete就不需要写了
        ////注意这里的Executor所属的包是org.apache.ibatis.executor
        {@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
        })
public class DynamicDataSourceInterceptor implements Interceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(DynamicDataSourceInterceptor.class);
    private static final Pattern PATTERN = Pattern.compile(".*insert\\u0020.*|.*delete\\u0020.*|.*update\\u0020.*");

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //判断本次执行是否被事务管理
        boolean synchronizationActive = TransactionSynchronizationManager.isActualTransactionActive();
        //获取mybatis传过来的参数
        Object[] args = invocation.getArgs();
        //sql是属于哪种操作（增删改查）往往是保存在第一个对象中
        MappedStatement ms = (MappedStatement) args[0];
        String lookupKey = DynamicDataSourceHolder.DB_MASTER;
        if (!synchronizationActive) {
            //如果是读操作
            if (ms.getSqlCommandType().equals(SqlCommandType.SELECT)) {
                //selectKey为自增id查询主键 SELECT LAST_INSERT_ID()方法，使用主库
                if (ms.getId().contains(SelectKeyGenerator.SELECT_KEY_SUFFIX)) {
                    lookupKey = DynamicDataSourceHolder.DB_MASTER;
                } else {
                    BoundSql boundSql = ms.getSqlSource().getBoundSql(args[1]);
                    String sql = boundSql.getSql().toLowerCase(Locale.CHINA)
                            .replaceAll("[\\t\\n\\r]", " ");//将所有的制表符换行符回车符替换掉
                    //匹配sql语句是否为增删改
                    if (PATTERN.matcher(sql).matches()) {
                        lookupKey = DynamicDataSourceHolder.DB_MASTER;
                    } else {
                        lookupKey = DynamicDataSourceHolder.DB_SLAVE;
                    }
                }
            }
        } else {
            //用事务管理的操作一般都是写操作，因此我们用主库
            lookupKey = DynamicDataSourceHolder.DB_MASTER;
        }
        LOGGER.debug("设置方法[{}], use[{}], Strategy, SqlCommandType[{}]...",
                ms.getId(), lookupKey, ms.getSqlCommandType().name());
        DynamicDataSourceHolder.setDbType(lookupKey);
        return invocation.proceed();
    }
}

